package com.joinway.framework.extension.image;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.ImagingOpException;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public final class ImageUtils {

	/**
	 * 调整图片大小
	 * 
	 * @param source
	 *            原始图片路径
	 * @param target
	 *            缩放后的图片保存路径
	 * @param percentage
	 *            缩放比率
	 * @throws IOException io异常
	 */
	public static void resize(String source, String target, int percentage)
			throws IOException {
		if (percentage <= 0) {
			throw new ImagingOpException("Error:不合法的参数:percentage" + percentage
					+ ",percentage应该大于0");
		}
		File file = new File(source);
		String fileName = file.getName();
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

		BufferedImage src = ImageIO.read(file);
		int type = src.getColorModel().getTransparency();
		int width = src.getWidth() * percentage / 100;
		int height = src.getHeight() * percentage / 100;

		RenderingHints renderingHints = new RenderingHints(
				RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_ANTIALIAS_ON);

		renderingHints.put(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BICUBIC);

		BufferedImage img = new BufferedImage(width, height, type);
		Graphics2D graphics2d = img.createGraphics();
		graphics2d.setRenderingHints(renderingHints);
		graphics2d.drawImage(src, 0, 0, width, height, 0, 0, src.getWidth(),
				src.getHeight(), null);
		graphics2d.dispose();

		ImageIO.write(img, suffix, new File(target));
	}

	/**
	 * 调整图片大小
	 * @param source
	 * @param percentage
	 * @return
	 */
	public static byte[] resize(byte[] source, int percentage){
		return null;
	}
	
	/**
	 * 
	 * @param source
	 * @param percentage
	 * @return
	 */
	public static byte[] resize(String source, int percentage){
		return null;
	}
	
	private ImageUtils() {
	}

}
